//自调用构造函数--游戏对象
(function() {
	function Game(map) {
		that = null;
		this.food = new Food();
		this.snake = new Snake();
		this.map = map;
		that = this; //保存当前变量到that中
	}
	//初始化游戏
	Game.prototype.init = function() {
		//初始化食物
		this.food.init(this.map);
		//初始化小蛇
		this.snake.init(this.map);
		//调用小蛇自己跑的函数
		this.runSnake(this.food, this.map);
		//在这里调用键盘按下事件
		this.bindKey();
	};

	//添加原型方法，小蛇可以自动的跑起来
	Game.prototype.runSnake = function(food, map) {
		//自动的移动，所以需要一个定时器
		var timeId = setInterval(function() {
			//当前this指的是window
			this.snake.move(food, map);
			this.snake.init(map);
			//设置移动时候坐标的最大值
			var maxX = map.offsetWidth / this.snake.width;
			var maxY = map.offsetHeight / this.snake.height;
			//蛇头的坐标
			var headX = this.snake.body[0].x;
			var headY = this.snake.body[0].y;
			//小蛇蛇头超过最大值，就停止定时器，并说，撞墙啦
			if(headX < 0 || headX >= maxX) {
				clearInterval(timeId);
				alert("Game over");
			}
			if(headY < 0 || headY >= maxY) {
				clearInterval(timeId);
				alert("Game over");
			}
		}.bind(that), 150);
	}
	//添加原型方法，获得键盘按下的方向，给小蛇，改变小蛇的移动方向
	Game.prototype.bindKey = function() {
		//获取用户按下的按键，改变小蛇的运动方向
		document.addEventListener("keydown", function(e) {
			//这个时候的this应该是触发键盘按下事件的对象，也就是document
			//键盘按下的每一个操作，都对应有一个唯一的keyCode;
			//获取键盘按下的值
			switch(e.keyCode) {
				case 37:
					this.snake.direction = "left";
					break;
				case 38:
					this.snake.direction = "top";
					break;
				case 39:
					this.snake.direction = "right";
					break;
				case 40:
					this.snake.direction = "bottom";
					break;
			}
		}.bind(that), false);
	};

	window.Game = Game;
}());